﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using BLL;
using System.IO;
using System.IO.Compression;
using System.Collections;
using Model;
using System.Threading;
using System.Xml.Serialization;
using System.Xml;
using System.Runtime.Serialization.Formatters.Binary;

namespace Sales
{
    public partial class SynchTool : Form
    {
        public static string config_dir = Application.StartupPath + "/config";
        public static string config_file = config_dir + "/config.xml";
        public SysConfig config;
        public Common2 common = new Common2();
        string url = "";// ConfigurationSettings.AppSettings["WebService"].ToString();
        private BasicBLL cpdaHBLL;


        #region 页面属性
        public string Dmbh
        {
            get;
            set;
        }
        #endregion
        public SynchTool()
        {
            InitializeComponent();
            config = Common2.GetConfig();//获取相关配置属性 
            url = config.WebService;
        }

        private void SynchTool_Load(object sender, EventArgs e)
        {

        }

        private void DoWork(int type)
        {
            this.osProgress1.AutoProgress = true;
            ThreadPool.QueueUserWorkItem(new WaitCallback(this.OptData), type);
        }
        private void OptData(object o)
        {
            int type = (int)o;

            if (type == 0)
            {
                UpLoadData(o);
            }
            else
            {
                CheckXsdH();
            }
        }
        private void DownloadWork(int type)
        {
            if (type == 0)
            {
                this.osProgress2.AutoProgress = true;

            }
            else
            {
                this.osProgress3.AutoProgress = true;

            }

            ThreadPool.QueueUserWorkItem(new WaitCallback(this.DownloadData), type);
        }


        private void UpLoadData(object o)
        {
            BasicBLL basicBLL = new BasicBLL();
            // int Count = basicBLL.GetxskdHCount(" where  djstate=0");//待上传销售单记录数
            int Size = 20;//一次提取数量
            int pageIndex = 1;
            bool doing = true;
            string userName = "";
            DataTable dt = new DataTable();

            DataSet dsH = new DataSet();
            DataSet dsB = new DataSet();
            int count = 0;
            while (true)
            {
                dt = basicBLL.GetpfdHData(Size, pageIndex, ref count);

                if (dt != null && dt.Rows.Count > 0)
                {
                    dsH.Clear();
                    dsB.Clear();

                    dsH = new DataSet();
                    dsB = new DataSet();
                    dsH.Tables.Add(dt);//填装 表头部分
                    foreach (DataRow dr in dt.Rows)
                    {
                        xskdh xskdhModel = basicBLL.GetXskdhEntity(dr);// basicBLL.GetXskdhModel(dr["xsdh"].ToString());
                        userName = xskdhModel.djyh;
                        DataSet xskdbDs = basicBLL.GetxskdBDataDs("  where djlsh=" + dr["djlsh"].ToString());
                        dsB = FilledDs(dsB, xskdbDs.Tables[0]);
                    }

                    byte[] dtXskdh = GetDataSetSurrogateZipBYtes(dsH);

                    byte[] dtXskdb = GetDataSetSurrogateZipBYtes(dsB);


                    NewTransportObject transportobject = new NewTransportObject();
                    transportobject.StrXskdH = dtXskdh;
                    transportobject.DtXskdb = dtXskdb;
                    ArrayList parms = new ArrayList();
                    parms.Add(transportobject.StrXskdH);
                    parms.Add(transportobject.DtXskdb);
                    string reslut = DSWebService.InvokeWebService(url, "InsertYw_pfd", parms.ToArray());

                    if (int.Parse(reslut) > 0)
                    {
                        ArrayList parms2 = new ArrayList();
                        if (userName == null)
                            userName = "";
                        parms2.Add(userName);
                        reslut = DSWebService.InvokeWebService(url, "CheckXskdh", parms2.ToArray());

                        //修改本地数据库 xskdh状态
                        int s3 = basicBLL.UpdatexskdhStatus(dt);
                    }
                    else if (int.Parse(reslut) == -2)
                    {
                        this.osProgress1.AutoProgress = false;
                        doing = false;
                        MessageBox.Show(" 无法连接目标服务器请检查网络！ ");
                        break;
                    }
                    else
                    {
                        this.osProgress1.AutoProgress = false;
                        doing = false;
                        MessageBox.Show("连接成功，但 数据上传失败请联系管理员！ ");
                        break;
                    }
                }
                else
                {
                    break;
                }
                pageIndex++;
            }
            this.osProgress1.AutoProgress = false;
            if (doing)
            {
                if (o.ToString() == "1")
                {
                    if (count > 0)
                    {
                        MessageBox.Show(" 上传完成 总共记录数目：" + count);
                    }
                }
                else
                {
                    MessageBox.Show(" 上传完成 总共记录数目：" + count);
                }
            }
        }

        private void CheckXsdH()
        {
            string userName = "上传人";
            ArrayList parms2 = new ArrayList();
            parms2.Add(userName);

            string reslut = DSWebService.InvokeWebService(url, "CheckXskdh", parms2.ToArray());
            //库存总表不存在

            if (reslut.Contains("-3"))
            {

                string[] s1 = reslut.Split(',');
                if (s1.Length == 3)
                {

                    string msg = "有商品部存在本月库存(库存总表无数据)！";
                    string count1 = s1[1];
                    string count2 = s1[2];
                    if (count1 != "")
                    {
                        msg += "其中 销售单中" + count1 + "种商品未审核 ";
                    }

                    if (count2 != "")
                    {
                        msg += "其中 退货单中" + count2 + "种商品未审核 ";
                    }



                    MessageBox.Show(msg);
                }

            }

            else if (reslut == "-1")
            {
                MessageBox.Show(" 当前没有待审核数据！ ");
            }
            else if (reslut == "0")
            {
                MessageBox.Show(" 数据审核失败请联系管理员！ ");
            }
            else
            {
                MessageBox.Show(" 审核成功！ ");
            }
            this.osProgress1.AutoProgress = false;
        }


        private void DownloadData(object o)
        {
            int type = (int)o;

            if (type == 0)
            {

                DownloadGetCpdaH();
            }
            else
            {

                DownloadGetYyyH();
            //    DownloadGetDmdaHH();
                //DownloadGetKhdaH();
                //DownloadGetDmdaHH();
                //DownloadGetBmdaHH();
                this.osProgress3.AutoProgress = false;
            }
        }

        private void DownloadGetCpdaH()
        {
            ArrayList parms = new ArrayList();
            cpdaHBLL = new BasicBLL();
            string reslut = "";
            string strWhere = "";
            // string strWhere2 = "";
            if (radioButton3.Checked)
            {
                string startTime = this.dateTimePicker4.Value.ToString("yyyy-MM-dd") + " 00:00:00";
                string endTime = this.dateTimePicker3.Value.ToString("yyyy-MM-dd") + " 23:59:59";

                strWhere = "(( xgsj>='" + startTime + "' and xgsj<='" + endTime + "') or ( djsj>='" + startTime + "' and djsj<='" + endTime + "'))";

            }

            int count = 0;
            int pageIndex = 1;
            int pageSize = 50;
            while (true)
            {
                parms.Clear();
                parms.Add(strWhere);
                parms.Add(pageSize);
                parms.Add(pageIndex);

                reslut = DSWebService.InvokeWebService(url, "GetCpdaData2", parms.ToArray());
                if (reslut != "-2" && reslut != "")
                {
                    pageIndex++;
                    DataTable dt = DeserializeDataTable(reslut);
                    count += dt.Rows.Count;
                    //插入数据库
                    foreach (DataRow newdr in dt.Rows)
                    {
                        string spbh = newdr["spbh"].ToString();
                        SpdaHModel model = cpdaHBLL.GetspdaHModel(newdr);
                        if (cpdaHBLL.IsExistSpbh(spbh))
                        {
                            bool s1 = cpdaHBLL.UpdatespdaHModel(model);
                        }
                        else
                        {
                            bool s2 = cpdaHBLL.AddspdaHModel(model);
                        }
                    }
                }
                else
                {
                    break;
                }
            }
            if (count > 0)
            {
                this.osProgress2.AutoProgress = false;
                MessageBox.Show(" 下载完成！ 共计下载数据" + count + "条");
            }
            else
            {

                this.osProgress2.AutoProgress = false;
                MessageBox.Show(" 本时间段未获取到数据，可能网络原因，可能本时间段无更新数据！ ");
            }



        }
        private void DownloadGetYyyH()
        {
            ArrayList parms = new ArrayList();
            cpdaHBLL = new BasicBLL();
            string reslut = "";

            if (radioButton1.Checked)
            {
                  reslut = "dmbh='" + Dmbh + "'";
            }

            parms.Add(reslut);
            reslut = DSWebService.InvokeWebService(url, "GetYyyData", parms.ToArray());

            if (reslut != "-2")
            {

                if (reslut != "")
                {
                    DataTable dt = DeserializeDataTable(reslut);
                    //插入数据库
                    foreach (DataRow newdr in dt.Rows)
                    {
                        string ygbh = newdr["ygbh"].ToString();
                        yyydaHModel model = cpdaHBLL.GetyyydaHModel(newdr);
                        if (cpdaHBLL.IsExistYyy(ygbh))
                        {
                            bool s1 = cpdaHBLL.Updatejbxx_yyydaHModel(model);
                        }
                        else
                        {
                            bool s2 = cpdaHBLL.Addjbxx_yyydaHModel(model);
                        }
                    }

                    //  this.osProgress3.AutoProgress = false;
                    MessageBox.Show("营业员信息 下载完成 ");
                }
                else
                {
                    MessageBox.Show("营业员信息 无数据下载 ");
                }




            }
            else
            {
                // this.osProgress3.AutoProgress = false;
                MessageBox.Show(" 无法连接目标服务器请检查网络！提取营业员信息失败 ");
            }
        }

        /// <summary>
        /// 下载客户信息
        /// </summary>
        private void DownloadGetKhdaH()
        {
            ArrayList parms = new ArrayList();
            cpdaHBLL = new BasicBLL();
            

            string reslut = "";

            if (radioButton1.Checked)
            {
                reslut = "dmbh='" + Dmbh + "'";
            }


            parms.Add(reslut);
            reslut = DSWebService.InvokeWebService(url, "GetKhdaHData", parms.ToArray());

            if (reslut != "-2")
            {
                if (reslut != "")
                {
                    DataTable dt = DeserializeDataTable(reslut);
                    //插入数据库
                    foreach (DataRow newdr in dt.Rows)
                    {
                        string khbh = newdr["kh"].ToString();
                        HykblHModel model = cpdaHBLL.GetkhdaHModel(newdr);
                        if (cpdaHBLL.IsExistKhxx(khbh))
                        {
                            bool s1 = cpdaHBLL.Updatejbxx_khdaH(model);
                        }
                        else
                        {
                            bool s2 = cpdaHBLL.Addjbxx_khdaH(model);
                        }
                    }
                    //  this.osProgress3.AutoProgress = false;
                    MessageBox.Show(" 会员信息 下载完成 ");
                }
                else
                {
                    MessageBox.Show("营业员信息 无数据下载 ");
                }
            }
            else
            {
                //this.osProgress3.AutoProgress = false;
                MessageBox.Show(" 无法连接目标服务器请检查网络！提取会员信息失败 ");
            }
        }

        /// <summary>
        /// 下载店面信息
        /// </summary>
        private void DownloadGetDmdaHH()
        {
            ArrayList parms = new ArrayList();
            cpdaHBLL = new BasicBLL();
            string reslut = "";

            parms.Add("");
            reslut = DSWebService.InvokeWebService(url, "GetDmdaHData", parms.ToArray());

            if (reslut != "-2")
            {
                if (reslut != "")
                {
                    DataTable dt = DeserializeDataTable(reslut);
                    //插入数据库
                    foreach (DataRow newdr in dt.Rows)
                    {
                        string dmbh = newdr["dmbh"].ToString();

               
                        dmdaHModel model = cpdaHBLL.GetdmdaHModel(newdr);
                        if (cpdaHBLL.IsExistDmxx(dmbh))
                        {
                            bool s1 = cpdaHBLL.UpdatedmdaH(model);
                        }
                        else
                        {
                            bool s2 = cpdaHBLL.AdddmdaH(model);
                        }
                    }
                    //  this.osProgress3.AutoProgress = false;
                    MessageBox.Show(" 店面信息 下载完成 ");

                }
                else
                {
                    MessageBox.Show("营业员信息 无数据下载 ");
                }
            }
            else
            {
                //this.osProgress3.AutoProgress = false;
                MessageBox.Show(" 无法连接目标服务器请检查网络！提取店面信息失败 ");
            }
        }


        /// <summary>
        /// 下载部门信息
        /// </summary>
        private void DownloadGetBmdaHH()
        {
            ArrayList parms = new ArrayList();
            cpdaHBLL = new BasicBLL();
            string reslut = "";

            parms.Add("");
            reslut = DSWebService.InvokeWebService(url, "GetBmdaHData", parms.ToArray());

            if (reslut != "-2")
            {
                if (reslut != "")
                {
                    DataTable dt = DeserializeDataTable(reslut);
                    //插入数据库
                    foreach (DataRow newdr in dt.Rows)
                    {
                        string bmbh = newdr["bmbh"].ToString();
                        bmdaHModel model = cpdaHBLL.GetbmdaHModel(newdr);
                        if (cpdaHBLL.IsExistDmxx(bmbh))
                        {
                            bool s1 = cpdaHBLL.UpdatebmdaH(model);
                        }
                        else
                        {
                            bool s2 = cpdaHBLL.AddbmdaH(model);
                        }
                    }

                    MessageBox.Show(" 部门信息 下载完成 ");

                }
                else
                {
                    MessageBox.Show("营业员信息 无数据下载 ");
                }

            }
            else
            {

                MessageBox.Show(" 无法连接目标服务器请检查网络！提取部门信息失败 ");
            }
        }



        private DataSet FilledDs(DataSet ds, DataTable dt)
        {
            if (ds.Tables.Count > 0)
            {
                object[] obj = new object[dt.Columns.Count];
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    dt.Rows[i].ItemArray.CopyTo(obj, 0);
                    ds.Tables[0].Rows.Add(obj);
                }
            }
            else
            {
                DataTable ndt = dt.Copy();
                ds.Tables.Add(ndt);
            }

            return ds;

        }

        #region 序列化 反序列化




        /// 序列化DataTable
        /// </summary>
        /// <param name="pDt">包含数据的DataTable</param>
        /// <returns>序列化的DataTable</returns>
        public static string SerializeDataTableXml(DataTable pDt, string pdtname)
        {
            // 序列化DataTable
            pDt.TableName = pdtname;
            StringBuilder sb = new StringBuilder();
            XmlWriter writer = XmlWriter.Create(sb);
            XmlSerializer serializer = new XmlSerializer(typeof(DataTable));
            serializer.Serialize(writer, pDt);
            writer.Close();
            return sb.ToString();
        }




        ///序列化转化为二进制数组的DataSet
        public byte[] GetDataSetSurrogateZipBYtes(DataSet DS)
        {
            DataSetSurrogate dss = new DataSetSurrogate(DS);
            ///二进制方式方式序列化

            BinaryFormatter ser = new BinaryFormatter();
            MemoryStream ms = new MemoryStream();
            ser.Serialize(ms, dss);
            byte[] buffer = ms.ToArray();
            ///调用压缩方法

            byte[] Zipbuffer = Compress(buffer);
            return Zipbuffer;
        }
        ///压缩二进制文件
        private byte[] Compress(byte[] data)
        {
            MemoryStream ms = new MemoryStream();
            Stream zipStream = null;
            zipStream = new GZipStream(ms, CompressionMode.Compress, true);

            ///从指定的字节数组中将压缩的字节写入基础流

            zipStream.Write(data, 0, data.Length);
            zipStream.Close();
            ms.Position = 0;
            byte[] Compressed_Data = new byte[ms.Length];
            ms.Read(Compressed_Data, 0, int.Parse(ms.Length.ToString()));
            return Compressed_Data;
        }



        ///将压缩后的二进制数组解压

        public static byte[] Decompress(byte[] data)
        {      ///data参数为压缩后的二进制数组
            try
            {
                MemoryStream ms = new MemoryStream(data);
                Stream zipStream = null;
                zipStream = new GZipStream(ms, CompressionMode.Decompress);
                byte[] dc_data = null;
                dc_data = EtractBytesFormStream(zipStream, data.Length);
                return dc_data;

                ///返回解压后的二进制数组
            }
            catch
            {
                return null;
            }
        }


        public static byte[] EtractBytesFormStream(Stream zipStream, int dataBlock)
        {
            try
            {
                byte[] data = null;
                int totalBytesRead = 0;
                while (true)
                {
                    Array.Resize(ref data, totalBytesRead + dataBlock + 1);
                    int bytesRead = zipStream.Read(data, totalBytesRead, dataBlock);
                    if (bytesRead == 0)
                    {
                        break;
                    }
                    totalBytesRead += bytesRead;
                }
                Array.Resize(ref data, totalBytesRead);
                return data;
            }
            catch
            {
                return null;
            }
        }


        /// 将二进制文件反序列化后转化为DataSet

        public DataSet GetDatasetFromByte(byte[] ZipByte)
        {
            byte[] buffer = Decompress(ZipByte);
            BinaryFormatter ser = new BinaryFormatter();
            DataSetSurrogate dss;
            dss = (DataSetSurrogate)ser.Deserialize(new MemoryStream(buffer));
            DataSet DS = dss.ConvertToDataSet();
            return DS;

        }


        /// <summary>
        /// 反序列化DataTable
        /// </summary>
        /// <param name="pXml">序列化的DataTable</param>
        /// <returns>DataTable</returns>
        public static DataTable DeserializeDataTable(string pXml)
        {

            StringReader strReader = new StringReader(pXml);
            XmlReader xmlReader = XmlReader.Create(strReader);
            XmlSerializer serializer = new XmlSerializer(typeof(DataTable));

            DataTable dt = serializer.Deserialize(xmlReader) as DataTable;
            return dt;
        }


        #endregion

        private void gbtnUpload_Click(object sender, EventArgs e)
        {
            DoWork(0);
        }

        private void gbtnCheck_Click(object sender, EventArgs e)
        {
            DoWork(1);
        }

        private void gbtnSPDownLoad_Click(object sender, EventArgs e)
        {
            DownloadWork(0);
        }

        private void gbtnHYDownLoad_Click(object sender, EventArgs e)
        {
            DownloadWork(1);
        }


    }
}
